#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "MessageTypes.h"
#include "ConnectionString.h"
#include "Comtools.h"
#include "TraceDlg.h"
#include "ComponentsDlg.h"

#include <QMessageBox>
#include <QItemSelectionModel>
#include <QFileDialog>
#include <sstream>

#import "msado15.dll" rename_namespace("ADODB") rename("EOF", "ADOEOF")  

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    pAbstrGauge(NULL),
    pAbstrGauge2(NULL), 
    pAbstrGauge3(NULL), 
    pAbstrGauge4(NULL),
    pGauge(NULL),
    pGauge2(NULL),
    pGauge3(NULL), 
    pGauge4(NULL),
    m_pBusSend(NULL),
    m_pBusListen(NULL),
    m_pBusAbstrListen(NULL),
    pController(NULL),
    m_lLogId(0),
    m_pSendMeta(NULL),
    pActionAllCompenents(NULL),
    pActionControllerMaster(NULL)
{
    ui->setupUi(this);

    createActions();

    ui->menuComponents_2->addAction(pActionAllCompenents);
    ui->menuComponents_2->addAction(pActionStartGauge);
    ui->menuComponents_2->addAction(pActionStartAbstrGauge);
    ui->menuComponents_2->addAction(pActionStartCtrl);

    ui->menuDeployment->addAction(pActionUploadMetadata);
    ui->menuDeployment->addAction(pActionExpandEvents);
    ui->menuDeployment->addAction(pActionExpandActions);
    ui->menuDeployment->addAction(pActionSep);
    ui->menuDeployment->addAction(pActionDelMetadata);

    ui->menuTest->addAction(pActionSendDummyTrace);
    ui->menuTest->addAction(pActionDelAllMsg);
    ui->menuTest->addAction(pActionDelEvtScheme);

    ui->menuFile->addAction(pActionFetchLog);
    ui->menuFile->addAction(pActionClearLog);
    ui->menuFile->addAction(pActionSep);
    ui->menuFile->addAction(pActionExit);
    
    ui->menuSettings->addAction(pActionControllerMaster);
    ui->menuSettings->addAction(pActionComponentList);
    ui->menuSettings->addAction(pActionSep);
    ui->menuSettings->addAction(pActionDelComponentRegistry);

    connect(ui->pushButtonClose, SIGNAL(clicked()), this, SLOT(exitPrg()));
    connect(ui->pushButtonShowTrace, SIGNAL(clicked()), this, SLOT(showTrace()));
    connect(ui->tableWidgetLog, SIGNAL(cellClicked(int,int)), this, SLOT(clickedLog()));
}

void MainWindow::clickStartAllComponents()
{
    startGauge();
    startAbstrGauge();
    startCtrl();
  
    pActionAllCompenents->setChecked(!pActionAllCompenents->isChecked());
}

void MainWindow::createActions()
{
    pActionControllerMaster = new QAction(QIcon(), tr("Promote to master"), this);
    pActionControllerMaster->setStatusTip(tr("Start all components"));
    connect(pActionControllerMaster, SIGNAL(triggered()), this, SLOT(clickPromoteToMaster()));

    pActionAllCompenents = new QAction(QIcon(), tr("All components..."), this);
    pActionAllCompenents->setStatusTip(tr("All components..."));
    connect(pActionAllCompenents, SIGNAL(triggered()), this, SLOT(clickStartAllComponents()));

    pActionComponentList = new QAction(QIcon(), tr("Registered components"), this);
    pActionComponentList->setStatusTip(tr("Registered components"));
    connect(pActionComponentList, SIGNAL(triggered()), this, SLOT(clickComponentsList()));

    pActionDelComponentRegistry = new QAction(QIcon(), tr("Delete registry"), this);
    pActionDelComponentRegistry->setStatusTip(tr("Delete registry"));
    connect(pActionDelComponentRegistry, SIGNAL(triggered()), this, SLOT(clickDeleteRegistry()));

    pActionClearLog = new QAction(QIcon(), tr("Clear log"), this);
    pActionClearLog->setStatusTip(tr("Clear log"));
    connect(pActionClearLog, SIGNAL(triggered()), this, SLOT(clickClearLog()));

    pActionDelAllMsg = new QAction(QIcon(), tr("Delete queue"), this);
    pActionDelAllMsg->setStatusTip(tr("Clear log"));
    connect(pActionDelAllMsg, SIGNAL(triggered()), this, SLOT(clickDeleteQueue()));

    pActionDelMetadata = new QAction(QIcon(), tr("Delete metadata"), this);
    pActionDelMetadata->setStatusTip(tr("Clear log"));
    connect(pActionDelMetadata, SIGNAL(triggered()), this, SLOT(clickDeleteMetadata()));

    pActionDelEvtScheme = new QAction(QIcon(), tr("Delete event scheme"), this);
    pActionDelEvtScheme->setStatusTip(tr("Clear log"));
    connect(pActionDelEvtScheme, SIGNAL(triggered()), this, SLOT(clickDeleteEvtScheme()));

    pActionStartGauge = new QAction(QIcon(":/images/Gauge.gif"), tr("&Gauge..."), this);
    pActionStartGauge->setStatusTip(tr("Start/stop gauge"));
    pActionStartGauge->setCheckable(true);
    connect(pActionStartGauge, SIGNAL(triggered()), this, SLOT(startGauge()));

    pActionStartAbstrGauge = new QAction(QIcon(":/images/Gauge.gif"), tr("&Abstract Gauge..."), this);
    pActionStartAbstrGauge->setStatusTip(tr("Start/stop abstract gauge"));
    pActionStartAbstrGauge->setCheckable(true);
    connect(pActionStartAbstrGauge, SIGNAL(triggered()), this, SLOT(startAbstrGauge()));

    pActionStartCtrl = new QAction(QIcon(":/images/Execute2.png"), tr("&Controller..."), this);
    pActionStartCtrl->setStatusTip(tr("Start/stop controller"));
    pActionStartCtrl->setCheckable(true);
    connect(pActionStartCtrl, SIGNAL(triggered()), this, SLOT(startCtrl()));

    pActionExit = new QAction(QIcon(":/images/Exit.png"), tr("E&xit"), this);
    pActionExit->setStatusTip(tr("Exit application"));
    connect(pActionExit, SIGNAL(triggered()), this, SLOT(exitPrg()));

    pActionUploadMetadata = new QAction(QIcon(), tr("Upload metadata"), this);
    pActionUploadMetadata->setStatusTip(tr("Upload metadata"));
    connect(pActionUploadMetadata, SIGNAL(triggered()), this, SLOT(uploadMetadata()));
    //connect(pActionUploadMetadata, SIGNAL(triggered()), this, SLOT(sendMetadata()));

    pActionExpandEvents = new QAction(QIcon(), tr("Expand events"), this);
    pActionExpandEvents->setStatusTip(tr("Expand events"));
    connect(pActionExpandEvents, SIGNAL(triggered()), this, SLOT(expandEvents()));

    pActionExpandActions = new QAction(QIcon(), tr("Expand actions"), this);
    pActionExpandActions->setStatusTip(tr("Expand actions"));
    connect(pActionExpandActions, SIGNAL(triggered()), this, SLOT(expandActions()));

    pActionSendDummyTrace = new QAction(QIcon(), tr("Dummy traces"), this);
    pActionSendDummyTrace->setStatusTip(tr("Send dummy traces"));
    connect(pActionSendDummyTrace, SIGNAL(triggered()), this, SLOT(sendDummyTrace()));

    pActionShowTrace = new QAction(QIcon(":/images/Trace.png"), tr("Show trace"), this);
    pActionSendDummyTrace->setStatusTip(tr("Show trace for event"));
    connect(pActionShowTrace, SIGNAL(triggered()), this, SLOT(showTrace()));

    pActionFetchLog = new QAction(QIcon(), tr("Refresh log"), this);
    pActionFetchLog->setStatusTip(tr("Refresh log"));
    connect(pActionFetchLog, SIGNAL(triggered()), this, SLOT(fetchLog()));

    pActionSep = new QAction(this);
    pActionSep->setSeparator(true);
}


MainWindow::~MainWindow()
{
    delete ui;

    try { if (m_pBusSend) delete m_pBusSend; } catch (...) { }
    try { if (m_pBusListen) delete m_pBusListen; } catch (...) { }
    try { if (m_pBusAbstrListen) delete m_pBusAbstrListen; } catch (...) { }
    try { if (m_pSendMeta) delete m_pSendMeta; } catch (...) {}

    try { if (pAbstrGauge) delete pAbstrGauge; } catch (...) { }
    try { if (pAbstrGauge2) delete pAbstrGauge2; } catch (...) { }
    try { if (pAbstrGauge3) delete pAbstrGauge3; } catch (...) { }
    try { if (pAbstrGauge4) delete pAbstrGauge4; } catch (...) { }

    try { if (pGauge) delete pGauge; } catch (...) { }
    try { if (pGauge2) delete pGauge2; } catch (...) { }
    try { if (pGauge3) delete pGauge3; } catch (...) { }
    try { if (pGauge4) delete pGauge4; } catch (...) { }

    try { if (pController) delete pController; } catch (...) { }
}

void MainWindow::showTrace()
{
  int row = ui->tableWidgetLog->currentRow();
  if (0 > row) return;

  QString logId = ui->tableWidgetLog->item(row, 0)->text();
  QString appAlert = ui->tableWidgetLog->item(row, 3)->text();
  QString eventName = ui->tableWidgetLog->item(row, 4)->text();

  TraceDlg dlg(this);      
  dlg.setLogId(logId.toLong());
  dlg.setEventName(QString(appAlert + " - " + eventName).toAscii().constData());
  dlg.exec();
}

void MainWindow::startCtrl()
{
  if (!pController) {
    pController = new Controller();
    pActionStartCtrl->setChecked(true);
  } else {
    delete pController;
    pController = NULL;
    pActionStartCtrl->setChecked(false);
  }

  setWindowTitleMode();
}

void MainWindow::sendMetadata()
{
  QString	file = QFileDialog::getOpenFileName(this, 
                                              tr("Open Metadata File"), 
                                              "/", 
                                              tr("XML Files (*.xml);;All Files (*.*)"));

  HRESULT hr;
  VARIANT_BOOL b;
  BSTR name, xml;
  _bstr_t msg;
  IXMLDOMDocumentPtr pXMLDOMDoc; 
  IXMLDOMNodePtr pXMLDOMNode = NULL, pXMLDOMNode2 = NULL, pXMLDOMNodeAttr = NULL;
  IXMLDOMNodeListPtr pXMLDOMNodeList = NULL; 
  IXMLDOMNamedNodeMapPtr pXMLAttrs = NULL;

  pXMLDOMDoc.CreateInstance(__uuidof(DOMDocument));
  pXMLDOMDoc->put_async(false);
  pXMLDOMDoc->put_resolveExternals(false);

  VARIANT v;
  VariantInit(&v);
  v.bstrVal = _bstr_t(file.toAscii().constData());
  v.vt = VT_BSTR;
  hr = pXMLDOMDoc->load(v, &b);  

  if (S_OK == hr) {
    if (!m_pSendMeta) m_pSendMeta = new Dispatcher(METADATA);

    hr = pXMLDOMDoc->selectSingleNode(_bstr_t("event"), &pXMLDOMNode);
    if (S_OK == hr) { // data is event
      hr = pXMLDOMDoc->selectSingleNode(_bstr_t("event/name"), &pXMLDOMNode2);
      if (S_OK == hr) hr = pXMLDOMNode2->get_text(&name);
      if (S_OK == hr) hr = pXMLDOMDoc->get_xml(&xml);

      msg = "<change>"
            "  <events>"+ _bstr_t(xml) +"</events>"
            "</change>";

      m_pSendMeta->sendMessage(msg);
    } else {
      hr = pXMLDOMDoc->selectSingleNode(_bstr_t("action"), &pXMLDOMNode);
      if (S_OK == hr) { // data is action
        hr = pXMLDOMDoc->selectSingleNode(_bstr_t("action/name"), &pXMLDOMNode2);
        if (S_OK == hr) pXMLDOMNode2->get_text(&name);
        if (S_OK == hr) hr = pXMLDOMDoc->get_xml(&xml);

        msg = "<change>"
              "  <actions>"+ _bstr_t(xml) +"</actions>"
              "</change>";

        m_pSendMeta->sendMessage(msg);
      } else {
        ::MessageBox(NULL, "Unknown metadata", "Warning", MB_ICONWARNING | MB_OK);
      }
    }
  }
}

void MainWindow::uploadMetadata()
{
  QString	file = QFileDialog::getOpenFileName(this, 
                                              tr("Open Metadata File"), 
                                              "/", 
                                              tr("XML Files (*.xml);;All Files (*.*)"));

  HRESULT hr;
  VARIANT_BOOL b;
  BSTR name, xml;
  IXMLDOMDocumentPtr pXMLDOMDoc; 
  IXMLDOMNodePtr pXMLDOMNode = NULL, pXMLDOMNode2 = NULL, pXMLDOMNodeAttr = NULL;
  IXMLDOMNodeListPtr pXMLDOMNodeList = NULL, pXMLDOMNodePatternList = NULL;
  IXMLDOMNamedNodeMapPtr pXMLAttrs = NULL;

  pXMLDOMDoc.CreateInstance(__uuidof(DOMDocument));
  pXMLDOMDoc->put_async(false);
  pXMLDOMDoc->put_resolveExternals(false);

  VARIANT v;
  VariantInit(&v);
  v.bstrVal = _bstr_t(file.toAscii().constData());
  v.vt = VT_BSTR;
  hr = pXMLDOMDoc->load(v, &b);  

  if (S_OK == hr) {
    ADODB::_ConnectionPtr c; 
    hr = c.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
    if (S_OK != hr) throw("CreateInstance failed");
    hr = c->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  

    hr = pXMLDOMDoc->selectSingleNode(_bstr_t("event"), &pXMLDOMNode);
    if (S_OK == hr) { // data is event
      hr = pXMLDOMDoc->selectSingleNode(_bstr_t("event/name"), &pXMLDOMNode2);
      if (S_OK == hr) hr = pXMLDOMNode2->get_text(&name);
      if (S_OK == hr) hr = pXMLDOMDoc->get_xml(&xml);

      bstr_t sql = "delete from metadata where name = '"+ _bstr_t(name) +"' and type = 'EVENT'";

      try {      
        ADODB::_CommandPtr cmd;
        cmd.CreateInstance(__uuidof(ADODB::Command));
        cmd->ActiveConnection = c.GetInterfacePtr();
        cmd->CommandText = sql;
        cmd->Execute(NULL, NULL, ADODB::adCmdText);
      } catch (...) {
      }

      try {
        ADODB::_RecordsetPtr rs;  
        rs.CreateInstance (__uuidof(ADODB::Recordset));  
        rs->Open("METADATA", c.GetInterfacePtr(), ADODB::adOpenDynamic, ADODB::adLockOptimistic, ADODB::adCmdTable);  

        VARIANT v;
        VariantInit(&v);
        COMTools::PackVariant(&v, _bstr_t(xml), _bstr_t(xml).length());

        rs->AddNew();
        rs->Fields->GetItem(L"name")->Value = _bstr_t(name);
        rs->Fields->GetItem(L"type")->Value = _bstr_t("EVENT");
        rs->Fields->GetItem(L"format")->Value = v;
        rs->Update();
        try { rs->Close(); } catch (...) {}
      } catch (...) {
      }
    } else {
      hr = pXMLDOMDoc->selectSingleNode(_bstr_t("action"), &pXMLDOMNode);
      if (S_OK == hr) { // data is action
        hr = pXMLDOMDoc->selectSingleNode(_bstr_t("action/name"), &pXMLDOMNode2);
        if (S_OK == hr) pXMLDOMNode2->get_text(&name);
        if (S_OK == hr) hr = pXMLDOMDoc->get_xml(&xml);

        bstr_t sql = "delete from metadata where name = '"+ _bstr_t(name) +"' and type = 'ACTION'";

        try {
          ADODB::_CommandPtr cmd;
          cmd.CreateInstance(__uuidof(ADODB::Command));
          cmd->ActiveConnection = c.GetInterfacePtr();
          cmd->CommandText = sql;
          cmd->Execute(NULL, NULL, ADODB::adCmdText);
        } catch (...) {
        }

        try {
          ADODB::_RecordsetPtr rs;  
          rs.CreateInstance (__uuidof(ADODB::Recordset));  
          rs->Open("METADATA", c.GetInterfacePtr(), ADODB::adOpenDynamic, ADODB::adLockOptimistic, ADODB::adCmdTable);  

          VARIANT v;
          VariantInit(&v);
          COMTools::PackVariant(&v, _bstr_t(xml), _bstr_t(xml).length());

          rs->AddNew();
          rs->Fields->GetItem(L"name")->Value = _bstr_t(name);
          rs->Fields->GetItem(L"type")->Value = _bstr_t("ACTION");
          rs->Fields->GetItem(L"format")->Value = v;
          rs->Update();
          try { rs->Close(); } catch (...) {}
        } catch (...) {
        }
      } else {
        ::MessageBox(NULL, "Unknown metadata", "Warning", MB_ICONWARNING | MB_OK);
      }
    }    
    try { c->Close(); } catch (...) {}
  }
}

void MainWindow::expandActions()
{
  try {
    CoInitialize(NULL);

    HRESULT hr;
    
    const char* pszSql =  " select name, type, format, datalength(format) * 2 as datasize "
                          " from metadata "
                          " where type = 'ACTION' ";
    
    OutputDebugString(pszSql);

    _bstr_t sql = _bstr_t(pszSql);

    ADODB::_ConnectionPtr c; 
    hr = c.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
    if (S_OK != hr) throw("CreateInstance failed");
    hr = c->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  

    ADODB::_RecordsetPtr rs;  
    rs.CreateInstance (__uuidof(ADODB::Recordset));  
    rs->Open(sql, c.GetInterfacePtr(), ADODB::adOpenDynamic, ADODB::adLockOptimistic, ADODB::adCmdText);  

    if (!rs->ADOEOF) hr = rs->MoveFirst();
    while (S_OK == hr && !rs->ADOEOF) {          
      _bstr_t actionname = rs->Fields->GetItem(L"name")->GetValue();
      _bstr_t actiontype = rs->Fields->GetItem(L"type")->GetValue();

      long chunkSize = rs->Fields->GetItem(L"datasize")->GetValue();

      _variant_t val;
      BSTR bdata, xml = _bstr_t("");
      VariantInit(&val);
      val = rs->Fields->GetItem(L"format")->GetChunk(chunkSize * 2 + 2);
      COMTools::UnpackVariant(val, &bdata);
      VariantClear(&val);

      VARIANT_BOOL b;
      BSTR vMethodName, vDirection, vExecutable, vMsgID, 
           vSeqName, vSeqNo, vPatternText, vEventName,
           vDescription, vCommand;
      long lPatternSize = 0, lSetSize = 0;

      IXMLDOMDocumentPtr pXMLDOMDoc; 
      IXMLDOMNodePtr pXMLDOMNode = NULL, pXMLDOMNode2 = NULL, pXMLDOMNodeAttr = NULL;
      IXMLDOMNodeListPtr pXMLDOMNodeList = NULL, pXMLDOMNodePatternList = NULL;
      IXMLDOMNamedNodeMapPtr pXMLAttrs = NULL;

      pXMLDOMDoc.CreateInstance(__uuidof(DOMDocument));
      pXMLDOMDoc->put_async(false);
      pXMLDOMDoc->put_resolveExternals(false);
      hr = pXMLDOMDoc->loadXML(bdata, &b);

      ::SysFreeString(bdata);

      if (S_OK == hr) hr = pXMLDOMDoc->selectSingleNode(_bstr_t("//action/executable"), &pXMLDOMNode);
      if (S_OK == hr) hr = pXMLDOMNode->get_text(&vExecutable); 

      if (S_OK == hr) hr = pXMLDOMDoc->selectNodes(_bstr_t("//event/name"), &pXMLDOMNodeList);
      if (S_OK == hr) hr = pXMLDOMNodeList->get_length(&lSetSize);
      for (int seq=0; seq<lSetSize; ++seq) {
        if (S_OK == hr) hr = pXMLDOMNodeList->get_item(seq, &pXMLDOMNode);
        if (S_OK == hr) hr = pXMLDOMNode->get_text(&vEventName);

        {
          _bstr_t sqlDel = " delete from event_action where event_name = '" + _bstr_t(vEventName) + "' and action_name = '" + _bstr_t(actionname) + "' ";
          _bstr_t sqlIns = " insert into event_action (event_name, action_name) "
                           " select '" + _bstr_t(vEventName) + "', '" + _bstr_t(actionname) + "' ";

          OutputDebugString(sqlIns);

          try {
            ADODB::_ConnectionPtr c2; 
            hr = c2.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
            if (S_OK != hr) throw("CreateInstance failed");
            hr = c2->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  
            c2->Execute(sqlDel, NULL, ADODB::adExecuteNoRecords);
            c2->Execute(sqlIns, NULL, ADODB::adExecuteNoRecords);
            c2->Close();
          } catch (...) {
            OutputDebugString("* Store expanded metadata failed");
          }
        }
      }

      if (S_OK == hr) hr = pXMLDOMDoc->selectNodes(_bstr_t("//step"), &pXMLDOMNodeList);
      if (S_OK == hr) hr = pXMLDOMNodeList->get_length(&lSetSize);
      for (int step=0; step<lSetSize; ++step) {
        if (S_OK == hr) hr = pXMLDOMNodeList->get_item(step, &pXMLDOMNode);
        if (S_OK == hr) hr = pXMLDOMNode->get_attributes(&pXMLAttrs);
        if (S_OK == hr) hr = pXMLAttrs->getNamedItem(_bstr_t("sequence"), &pXMLDOMNodeAttr);
        if (S_OK == hr) hr = pXMLDOMNodeAttr->get_text(&vSeqNo);

        if (S_OK == hr) hr = pXMLDOMNode->selectSingleNode(_bstr_t("description"), &pXMLDOMNode2);
        if (S_OK == hr) hr = pXMLDOMNode2->get_text(&vDescription);
        if (S_OK == hr) hr = pXMLDOMNode->selectSingleNode(_bstr_t("command"), &pXMLDOMNode2);
        if (S_OK == hr) hr = pXMLDOMNode2->get_text(&vCommand);

        {
          bstr_t sqlDel = " delete from action where action_name = '" + _bstr_t(actionname) + "' and action_step = '" + _bstr_t(vSeqNo) + "' ";

          bstr_t sqlIns  = " insert into action (action_name, action_step, description, command) "
                           " select '" + _bstr_t(actionname) + "', '" + _bstr_t(vSeqNo) + "', '" + _bstr_t(vDescription) + "', '" + _bstr_t(vCommand) + "' ";
          try {
            ADODB::_ConnectionPtr c2; 
            hr = c2.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
            if (S_OK != hr) throw("CreateInstance failed");
            hr = c2->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  
            c2->Execute(sqlDel, NULL, ADODB::adExecuteNoRecords);
            c2->Execute(sqlIns, NULL, ADODB::adExecuteNoRecords);
            c2->Close();
          } catch (...) {
            OutputDebugString("* Store expanded metadata failed");
          }
        }

      }

      hr = rs->MoveNext();
    } 
    hr = rs->Close();
  } catch (_com_error &e) {
    BSTR b;
    if (e.ErrorInfo()) {
      e.ErrorInfo()->GetDescription(&b);
      char szErr[256];
      sprintf(szErr, "Error: %s\n",_com_util::ConvertBSTRToString(b));
      OutputDebugString(szErr);
    }
  } catch (...) {

  }
}

void MainWindow::expandEvents()
{
  try {
    CoInitialize(NULL);

    HRESULT hr;
    
    const char* pszSql =  " select name, type, format, datalength(format) * 2 as datasize "
                          " from metadata "
                          " where type = 'EVENT' ";
    
    OutputDebugString(pszSql);

    _bstr_t sql = _bstr_t(pszSql);

    ADODB::_ConnectionPtr c; 
    hr = c.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
    if (S_OK != hr) throw("CreateInstance failed");
    hr = c->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  

    ADODB::_RecordsetPtr rs;  
    rs.CreateInstance (__uuidof(ADODB::Recordset));  
    rs->Open(sql, c.GetInterfacePtr(), ADODB::adOpenDynamic, ADODB::adLockOptimistic, ADODB::adCmdText);  

    if (!rs->ADOEOF) hr = rs->MoveFirst();
    while (S_OK == hr && !rs->ADOEOF) {          
      _bstr_t eventname = rs->Fields->GetItem(L"name")->GetValue();
      _bstr_t eventtype = rs->Fields->GetItem(L"type")->GetValue();

      long chunkSize = rs->Fields->GetItem(L"datasize")->GetValue();

      _variant_t val;
      BSTR bdata, xml = _bstr_t("");
      VariantInit(&val);
      val = rs->Fields->GetItem(L"format")->GetChunk(chunkSize +2);
      COMTools::UnpackVariant(val, &bdata);
      VariantClear(&val);

      VARIANT_BOOL b;
      BSTR vMethodName, vDirection, vExecutable, vMsgID, vSeqName, vCategory,
           vSeqNo, vPatternMethod, vPatternClass, vSeverity;
      long lPatternSize = 0, lSetSize = 0;

      IXMLDOMDocumentPtr pXMLDOMDoc; 
      IXMLDOMNodePtr pXMLDOMNode = NULL, pXMLDOMNode2 = NULL, pXMLDOMNode3 = NULL, pXMLDOMNodeAttr = NULL;
      IXMLDOMNodeListPtr pXMLDOMNodeList = NULL, pXMLDOMNodePatternList = NULL;
      IXMLDOMNamedNodeMapPtr pXMLAttrs = NULL;

      pXMLDOMDoc.CreateInstance(__uuidof(DOMDocument));
      pXMLDOMDoc->put_async(false);
      pXMLDOMDoc->put_resolveExternals(false);
      hr = pXMLDOMDoc->loadXML(bdata, &b);

      ::SysFreeString(bdata);

      if (S_OK == hr) hr = pXMLDOMDoc->selectSingleNode(_bstr_t("//event"), &pXMLDOMNode);
      if (S_OK == hr) hr = pXMLDOMNode->get_attributes(&pXMLAttrs);
      if (S_OK == hr) hr = pXMLAttrs->getNamedItem(_bstr_t("severity"), &pXMLDOMNodeAttr);
      if (S_OK == hr) hr = pXMLDOMNodeAttr->get_text(&vSeverity); 

      if (S_OK == hr) hr = pXMLDOMDoc->selectSingleNode(_bstr_t("//executable"), &pXMLDOMNode);
      if (S_OK == hr) hr = pXMLDOMNode->get_text(&vExecutable); 

      if (S_OK == hr) hr = pXMLDOMDoc->selectSingleNode(_bstr_t("//category"), &pXMLDOMNode);
      if (S_OK == hr) hr = pXMLDOMNode->get_text(&vCategory); 

      if (S_OK == hr) hr = pXMLDOMDoc->selectNodes(_bstr_t("//sequence"), &pXMLDOMNodeList);
      if (S_OK == hr) hr = pXMLDOMNodeList->get_length(&lSetSize);
      for (int seq=0; seq<lSetSize; ++seq) {
        if (S_OK == hr) hr = pXMLDOMNodeList->get_item(seq, &pXMLDOMNode);
        if (S_OK == hr) hr = pXMLDOMNode->get_attributes(&pXMLAttrs);
        if (S_OK == hr) hr = pXMLAttrs->getNamedItem(_bstr_t("name"), &pXMLDOMNodeAttr);
        if (S_OK == hr) hr = pXMLDOMNodeAttr->get_text(&vSeqName);

        if (S_OK == hr) hr = pXMLDOMNode->selectNodes(_bstr_t("//pattern"), &pXMLDOMNodePatternList);
        if (S_OK == hr) hr = pXMLDOMNodePatternList->get_length(&lPatternSize);
        for (int ele=0; ele<lPatternSize; ++ele) {
          if (S_OK == hr) hr = pXMLDOMNodePatternList->get_item(ele, &pXMLDOMNode2);
          if (S_OK == hr) hr = pXMLDOMNode2->get_attributes(&pXMLAttrs);
          if (S_OK == hr) hr = pXMLAttrs->getNamedItem(_bstr_t("sequence"), &pXMLDOMNodeAttr);
          if (S_OK == hr) hr = pXMLDOMNodeAttr->get_text(&vSeqNo);
          if (S_OK == hr) hr = pXMLDOMNode2->selectSingleNode(_bstr_t("method"), &pXMLDOMNode3);
          if (S_OK == hr) hr = pXMLDOMNode3->get_text(&vPatternMethod);
          pXMLDOMNode3 = NULL;
          if (S_OK == hr) hr = pXMLDOMNode2->selectSingleNode(_bstr_t("class"), &pXMLDOMNode3);
          if (S_OK == hr) hr = pXMLDOMNode3->get_text(&vPatternClass);
          pXMLDOMNode3 = NULL;

          {
            bstr_t sqlDel = "delete from event_pattern where executable = '" + _bstr_t(vExecutable) + "' and event_name = '" + _bstr_t(eventname) + "' ";

            bstr_t sqlIns = " insert into event_pattern (executable, event_name, event_severity, seq_name, seq_number, seq_size, class_name, method_name, direction_type, event_category) "
                            " select '" + _bstr_t(vExecutable) + "', '" + _bstr_t(eventname) + "', '"+_bstr_t(vSeverity)+"', '" + _bstr_t(vSeqName) + "', '" + _bstr_t(vSeqNo) + "', '" + _bstr_t(lPatternSize) + "', '"+ _bstr_t(vPatternClass) +"', '" + _bstr_t(vPatternMethod) + "', '" + _bstr_t("entry") + "', '" + _bstr_t(vCategory) + "'";

            try {
              ADODB::_ConnectionPtr c2; 
              hr = c2.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
              if (S_OK != hr) throw("CreateInstance failed");
              hr = c2->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  
              if (0 == ele) c2->Execute(sqlDel, NULL, ADODB::adExecuteNoRecords);
              c2->Execute(sqlIns, NULL, ADODB::adExecuteNoRecords);
              c2->CommitTrans();
              c2->Close();
            } catch (...) {
              OutputDebugString("* Store expanded metadata failed");
            }
          }
        }
      }

      rs->MoveNext();
    } 
    hr = rs->Close();
  } catch (_com_error &e) {
    BSTR b;
    if (e.ErrorInfo()) {
      e.ErrorInfo()->GetDescription(&b);
      char szErr[256];
      sprintf(szErr, "Error: %s\n",_com_util::ConvertBSTRToString(b));
      OutputDebugString(szErr);
    }
  } catch (...) {

  }
}

void MainWindow::startGauge()
{
  if (!pGauge) {
    pGauge = new Gauge;
    pGauge2 = new Gauge;
    pGauge3 = new Gauge;
    pGauge4 = new Gauge;
    pActionStartGauge->setChecked(true);
  } else {
    delete pGauge;
    pGauge = NULL;
    delete pGauge2;
    pGauge2 = NULL;
    delete pGauge3;
    pGauge3 = NULL;
    delete pGauge4;
    pGauge4 = NULL;
    pActionStartGauge->setChecked(false);
  }
}

void MainWindow::startAbstrGauge()
{
  if (!pAbstrGauge) {
    pAbstrGauge = new AbstractGauge();
    pAbstrGauge2 = new AbstractGauge();
    pAbstrGauge3 = new AbstractGauge();
    pAbstrGauge4 = new AbstractGauge();

    pActionStartAbstrGauge->setChecked(true);
  } else {
    delete pAbstrGauge;
    pAbstrGauge = NULL;
    delete pAbstrGauge2;
    pAbstrGauge = NULL;
    delete pAbstrGauge3;
    pAbstrGauge = NULL;
    delete pAbstrGauge4;
    pAbstrGauge = NULL;

    pActionStartAbstrGauge->setChecked(false);
  }
}

void MainWindow::sendDummyTrace()
{
  if (!m_pBusSend) m_pBusSend = new Dispatcher(TRACES);
  
  _bstr_t xml1 = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"
                "<!DOCTYPE trace ["
                "<!ELEMENT trace        (component, object)>"
                "<!ELEMENT component    (filename, lineno?, executable, processid, threadid)>"
                "<!ELEMENT object       (class?, method)>"
                "<!ELEMENT filename     (#PCDATA)>"
                "<!ELEMENT lineno       (#PCDATA)>"
                "<!ELEMENT executable   (#PCDATA)>"
                "<!ELEMENT processid    (#PCDATA)>"
                "<!ELEMENT threadid     (#PCDATA)>"
                "<!ELEMENT class        (#PCDATA)>"
                "<!ELEMENT method       (#PCDATA)>"
                "<!ATTLIST method event (entry | exit) #REQUIRED>"
                "]>"
                "<trace>"
                "  <component>"
                "    <filename>"+ _bstr_t(__FILE__) +"</filename>"
                "    <lineno>"+ _bstr_t(__LINE__) +"</lineno>"
                "    <executable>TestBus.exe</executable>"
                "    <processid>"+_bstr_t(::GetCurrentProcessId())+"</processid>"
                "    <threadid>"+_bstr_t(::GetCurrentThreadId())+"</threadid>"
                "  </component>"
                "<object>"
                "  <class>CTestBusDlg</class>"
                "  <method event=\"entry\">OnBnClickedButtonSend1</method>"
                "</object>"
                "</trace>";

  _bstr_t xml2 = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"
                "<!DOCTYPE trace ["
                "<!ELEMENT trace        (component, object)>"
                "<!ELEMENT component    (filename, lineno?, executable, processid, threadid)>"
                "<!ELEMENT object       (class?, method)>"
                "<!ELEMENT filename     (#PCDATA)>"
                "<!ELEMENT lineno       (#PCDATA)>"
                "<!ELEMENT executable   (#PCDATA)>"
                "<!ELEMENT processid    (#PCDATA)>"
                "<!ELEMENT threadid     (#PCDATA)>"
                "<!ELEMENT class        (#PCDATA)>"
                "<!ELEMENT method       (#PCDATA)>"
                "<!ATTLIST method event (entry | exit) #REQUIRED>"
                "]>"
                "<trace>"
                "  <component>"
                "    <filename>"+ _bstr_t(__FILE__) +"</filename>"
                "    <lineno>"+ _bstr_t(__LINE__) +"</lineno>"
                "    <executable>TestBus.exe</executable>"
                "    <processid>"+_bstr_t(::GetCurrentProcessId())+"</processid>"
                "    <threadid>"+_bstr_t(::GetCurrentThreadId())+"</threadid>"
                "  </component>"
                "<object>"
                "  <class>CTestBusDlg</class>"
                "  <method event=\"entry\">OnBnClickedButtonSend2</method>"
                "</object>"
                "</trace>";

  _bstr_t xml3 = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"
                "<!DOCTYPE trace ["
                "<!ELEMENT trace        (component, object)>"
                "<!ELEMENT component    (filename, lineno?, executable, processid, threadid)>"
                "<!ELEMENT object       (class?, method)>"
                "<!ELEMENT filename     (#PCDATA)>"
                "<!ELEMENT lineno       (#PCDATA)>"
                "<!ELEMENT executable   (#PCDATA)>"
                "<!ELEMENT processid    (#PCDATA)>"
                "<!ELEMENT threadid     (#PCDATA)>"
                "<!ELEMENT class        (#PCDATA)>"
                "<!ELEMENT method       (#PCDATA)>"
                "<!ATTLIST method event (entry | exit) #REQUIRED>"
                "]>"
                "<trace>"
                "  <component>"
                "    <filename>"+ _bstr_t(__FILE__) +"</filename>"
                "    <lineno>"+ _bstr_t(__LINE__) +"</lineno>"
                "    <executable>TestBus.exe</executable>"
                "    <processid>"+_bstr_t(::GetCurrentProcessId())+"</processid>"
                "    <threadid>"+_bstr_t(::GetCurrentThreadId())+"</threadid>"
                "  </component>"
                "<object>"
                "  <class>CTestBusDlg</class>"
                "  <method event=\"entry\">OnBnClickedButtonSend3</method>"
                "</object>"
                "</trace>";
 
  m_pBusSend->sendMessage(xml1);

  m_pBusSend->sendMessage(xml2);

  m_pBusSend->sendMessage(xml3);
}

void MainWindow::exitPrg()
{
  QApplication::exit();
}

void MainWindow::fetchLog()
{
  try {
    CoInitialize(NULL);
    HRESULT hr;
    
    ui->tableWidgetProc->clearContents();
    ui->tableWidgetProc->setRowCount(0);
    ui->tableWidgetProc->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidgetProc->setSelectionBehavior(QAbstractItemView::SelectRows);
    
    ui->tableWidgetLog->clearContents();
    ui->tableWidgetLog->setRowCount(0);
    ui->tableWidgetLog->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidgetLog->setSelectionBehavior(QAbstractItemView::SelectRows);

    _bstr_t sql =  " select * from log_event order by log_id desc ";

    ADODB::_ConnectionPtr c; 
    hr = c.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
    if (S_OK != hr) throw("CreateInstance failed");
    hr = c->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  

    ADODB::_RecordsetPtr rs;  
    rs.CreateInstance (__uuidof(ADODB::Recordset));  
    rs->Open(sql, c.GetInterfacePtr(), ADODB::adOpenStatic, ADODB::adLockOptimistic, ADODB::adCmdText);  

    int row = 0;

    if (!rs->ADOEOF) hr = rs->MoveFirst();
    if (S_OK == hr) {
      ui->tableWidgetLog->setRowCount(rs->RecordCount);
      while (S_OK == hr && !rs->ADOEOF) {          
        _bstr_t logid = rs->Fields->GetItem(L"log_id")->GetValue();
        _bstr_t eventtime = rs->Fields->GetItem(L"event_time")->GetValue();
        _bstr_t app = rs->Fields->GetItem(L"application_name")->GetValue();
        _bstr_t alias = rs->Fields->GetItem(L"alias")->GetValue();
        _bstr_t eventname = rs->Fields->GetItem(L"event_name")->GetValue();
        _bstr_t eventsev = rs->Fields->GetItem(L"event_Severity")->GetValue();
        _bstr_t actionname = rs->Fields->GetItem(L"action_name")->GetValue();

        ui->tableWidgetLog->setItem(row, 0, new QTableWidgetItem((char*)logid));
        ui->tableWidgetLog->setItem(row, 1, new QTableWidgetItem((char*)eventtime));
        ui->tableWidgetLog->setItem(row, 2, new QTableWidgetItem((char*)app));
        ui->tableWidgetLog->setItem(row, 3, new QTableWidgetItem((char*)alias));
        ui->tableWidgetLog->setItem(row, 4, new QTableWidgetItem((char*)eventname));
        ui->tableWidgetLog->setItem(row, 5, new QTableWidgetItem((char*)eventsev));
        ui->tableWidgetLog->setItem(row, 6, new QTableWidgetItem((char*)actionname));

        row++;
        hr = rs->MoveNext();
      }
    }
    try { rs->Close(); } catch (...) {}
    try { c->Close(); } catch (...) {}
  } catch (_com_error& e) {
    BSTR b;
    if (e.ErrorInfo()) {
      e.ErrorInfo()->GetDescription(&b);
      char szErr[256];
      sprintf(szErr, "Error: %s\n",_com_util::ConvertBSTRToString(b));
      OutputDebugString(szErr);
    }
  } catch (...) {
  }
}

void MainWindow::clickedLog()
{
  int row = ui->tableWidgetLog->currentRow();
  if (0 > row) return;

  QString v = ui->tableWidgetLog->item(row, 0)->text();
  m_lLogId = v.toLong();

  fetchProc();
}

void MainWindow::fetchProc()
{
  try {
    CoInitialize(NULL);
    HRESULT hr;
    
    ui->tableWidgetProc->clearContents();
    ui->tableWidgetProc->setRowCount(0);
    ui->tableWidgetProc->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidgetProc->setSelectionBehavior(QAbstractItemView::SelectRows);

    _bstr_t sql =  " select * from log_procedure where log_id = "+ _bstr_t(m_lLogId) +" order by log_procedure_id ";

    ADODB::_ConnectionPtr c; 
    hr = c.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
    if (S_OK != hr) throw("CreateInstance failed");
    hr = c->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  

    ADODB::_RecordsetPtr rs;  
    rs.CreateInstance (__uuidof(ADODB::Recordset));  
    rs->Open(sql, c.GetInterfacePtr(), ADODB::adOpenStatic, ADODB::adLockOptimistic, ADODB::adCmdText);  

    int row = 0;

    if (!rs->ADOEOF) hr = rs->MoveFirst();
    if (S_OK == hr) {
      ui->tableWidgetProc->setRowCount(rs->RecordCount);
      while (S_OK == hr && !rs->ADOEOF) {          
        _bstr_t procid = rs->Fields->GetItem(L"log_procedure_id")->GetValue();
        _bstr_t actionname = rs->Fields->GetItem(L"action_name")->GetValue();
        _bstr_t step = rs->Fields->GetItem(L"step")->GetValue();
        _bstr_t description = rs->Fields->GetItem(L"description")->GetValue();
        _bstr_t command = rs->Fields->GetItem(L"command")->GetValue();
        _bstr_t status = rs->Fields->GetItem(L"status")->GetValue();

        ui->tableWidgetProc->setItem(row, 0, new QTableWidgetItem((char*)step));
        ui->tableWidgetProc->setItem(row, 1, new QTableWidgetItem((char*)description));
        ui->tableWidgetProc->setItem(row, 2, new QTableWidgetItem((char*)command));

        row++;
        hr = rs->MoveNext();
      }
    }
    try { rs->Close(); } catch (...) {}
    try { c->Close(); } catch (...) {}
  } catch (_com_error& e) {
    BSTR b;
    if (e.ErrorInfo()) {
      e.ErrorInfo()->GetDescription(&b);
      char szErr[256];
      sprintf(szErr, "Error: %s\n",_com_util::ConvertBSTRToString(b));
      OutputDebugString(szErr);
    }
  } catch (...) {
  }
}

void MainWindow::clickClearLog()
{
  int r = QMessageBox::warning(this, 
                               "Warning",  
                               "Do you really want to delete the content of the log?", 
                               QMessageBox::Yes | QMessageBox::No, 
                               QMessageBox::No);

  if (QMessageBox::Yes != r) return;

  HRESULT hr;
  ADODB::_ConnectionPtr c; 
  hr = c.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
  if (S_OK != hr) throw("CreateInstance failed");
  hr = c->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  

  const char* sql1 = "delete from log_event";
  const char* sql2 = "delete from log_procedure";
  const char* sql3 = "delete from log_trace";

  ADODB::_CommandPtr cmd;
  cmd.CreateInstance(__uuidof(ADODB::Command));
  cmd->ActiveConnection = c.GetInterfacePtr();
  cmd->CommandText = _bstr_t(sql3);
  cmd->Execute(NULL, NULL, ADODB::adCmdText);
  cmd->CommandText = _bstr_t(sql2);
  cmd->Execute(NULL, NULL, ADODB::adCmdText);
  cmd->CommandText = _bstr_t(sql1);
  cmd->Execute(NULL, NULL, ADODB::adCmdText);

  try { c->Close(); } catch (...) { }

  ui->tableWidgetProc->clearContents();
  ui->tableWidgetProc->setRowCount(0);
  ui->tableWidgetProc->setSelectionMode(QAbstractItemView::SingleSelection);
  ui->tableWidgetProc->setSelectionBehavior(QAbstractItemView::SelectRows);
  
  ui->tableWidgetLog->clearContents();
  ui->tableWidgetLog->setRowCount(0);
  ui->tableWidgetLog->setSelectionMode(QAbstractItemView::SingleSelection);
  ui->tableWidgetLog->setSelectionBehavior(QAbstractItemView::SelectRows);
}

void MainWindow::clickDeleteQueue()
{
  HRESULT hr;
  ADODB::_ConnectionPtr c; 
  hr = c.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
  if (S_OK != hr) throw("CreateInstance failed");
  hr = c->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  

  const char* sql1 = "delete from message_queue";

  ADODB::_CommandPtr cmd;
  cmd.CreateInstance(__uuidof(ADODB::Command));
  cmd->ActiveConnection = c.GetInterfacePtr();
  cmd->CommandText = _bstr_t(sql1);
  cmd->Execute(NULL, NULL, ADODB::adCmdText);

  try { c->Close(); } catch (...) { }
}

void MainWindow::clickDeleteMetadata()
{
  int r = QMessageBox::warning(this, 
                               "Warning", 
                               "Do you really want to delete all the metadata?", 
                               QMessageBox::Yes | QMessageBox::No, 
                               QMessageBox::No);

  if (r != QMessageBox::Yes) return;

  HRESULT hr;
  ADODB::_ConnectionPtr c; 
  hr = c.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
  if (S_OK != hr) throw("CreateInstance failed");
  hr = c->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  

  const char* sql1 = "delete from action";
  const char* sql2 = "delete from event_Action";
  const char* sql3 = "delete from event_pattern";
  const char* sql4 = "delete from metadata";

  ADODB::_CommandPtr cmd;
  cmd.CreateInstance(__uuidof(ADODB::Command));
  cmd->ActiveConnection = c.GetInterfacePtr();
#ifndef _DEBUG
  cmd->CommandText = _bstr_t(sql4);
  cmd->Execute(NULL, NULL, ADODB::adCmdText);
#endif
  cmd->CommandText = _bstr_t(sql3);
  cmd->Execute(NULL, NULL, ADODB::adCmdText);
  cmd->CommandText = _bstr_t(sql2);
  cmd->Execute(NULL, NULL, ADODB::adCmdText);
  cmd->CommandText = _bstr_t(sql1);
  cmd->Execute(NULL, NULL, ADODB::adCmdText);

  try { c->Close(); } catch (...) { }
}

void MainWindow::clickDeleteEvtScheme()
{
  HRESULT hr;
  ADODB::_ConnectionPtr c; 
  hr = c.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
  if (S_OK != hr) throw("CreateInstance failed");
  hr = c->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  

  const char* sql1 = "delete from event_scheme";

  ADODB::_CommandPtr cmd;
  cmd.CreateInstance(__uuidof(ADODB::Command));
  cmd->ActiveConnection = c.GetInterfacePtr();
  cmd->CommandText = _bstr_t(sql1);
  cmd->Execute(NULL, NULL, ADODB::adCmdText);

  try { c->Close(); } catch (...) { }
}

void MainWindow::clickDeleteRegistry()
{
  int r = QMessageBox::warning(this, 
                               "Warning", 
                               "You are about to modify the system settings.\n" 
                               "Do you really want to delete the component registry?", 
                               QMessageBox::Yes | QMessageBox::No, 
                               QMessageBox::No);

  if (r != QMessageBox::Yes) return;

  HRESULT hr;
  ADODB::_ConnectionPtr c; 
  hr = c.CreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER);  
  if (S_OK != hr) throw("CreateInstance failed");
  hr = c->Open(bstr_t(CONNECTSTRING), L"", L"", -1);  

  const char* sql1 = "delete from component_register";

  const char* sql2 = "delete from component_activity";

  ADODB::_CommandPtr cmd;
  cmd.CreateInstance(__uuidof(ADODB::Command));
  cmd->ActiveConnection = c.GetInterfacePtr();
  cmd->CommandText = _bstr_t(sql1);
  cmd->Execute(NULL, NULL, ADODB::adCmdText);
  //cmd->CommandText = _bstr_t(sql2);
  //cmd->Execute(NULL, NULL, ADODB::adCmdText);

  try { c->Close(); } catch (...) { }
}

void MainWindow::clickComponentsList()
{
  ComponentsDlg dlg(this);
  dlg.exec();
}

void MainWindow::clickPromoteToMaster()
{
  if (pController) {
    pController->setMaster(true);
    setWindowTitleMode();
  }
}

void MainWindow::setWindowTitleMode()
{
  if (pController && !pController->isMaster()) {
    setWindowTitle(QString("Proof of Concept - Consolidated Log") + QString(" - PASSIVE MODE"));
  } else {
    setWindowTitle("Proof of Concept - Consolidated Log");
  }
}